import React, { useEffect, useState } from "react";
import { View, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import Pop from './components/Pop'
import Down from './components/Down'
import City from '@/common/city'
import { toast } from '@/utils/utils'
import './index.scss'
function findNodePath(tree, targetValue) {
    // 递归遍历树，回溯法查找目标节点路径
    function traverse(nodes, path) {
        for (const node of nodes) {
            // 当前路径副本 + 当前节点
            const currentPath = [...path, node];

            // 找到目标节点直接返回路径
            if (node.value === targetValue) {
                return currentPath;
            }

            // 有子节点则继续递归查找
            if (node.children && node.children.length > 0) {
                const found = traverse(node.children, currentPath);
                if (found) return found; // 找到则终止回溯
            }
        }
        return null; // 当前分支未找到
    }

    // 初始化调用，返回结果或空数组
    return traverse(tree, []) || [];
}
function filterChildrenById(data, ids) {
    const result = [];

    // 递归遍历每个节点
    data.forEach(item => {
        // 如果当前节点有子节点，则递归检查子节点
        if (item.children && item.children.length > 0) {
            item.children.forEach(child => {
                // 如果子节点的value在目标id数组中，则添加到结果
                if (ids.includes(child.value)) {
                    result.push(child);
                }
            });
        }
    });

    return result;
}
function filterMajorById(data, ids, fieldConditions = {}) {
    console.log(data, ids, fieldConditions)
    const { value, childrenName, } = fieldConditions
    const result = [];
    // 递归遍历每个节点
    console.log(data, 'data........')
    data.forEach(item => {
        // 如果当前节点有子节点，则递归检查子节点
        if (item[childrenName] && item[childrenName].length > 0) {
            item[childrenName].forEach(child => {
                if (ids.includes(String(child[value]))) {
                    result.push(child);
                }
            });
        }
    });

    return result;
}
const filterList = (val, fieldConditions = {}) => {
    console.log(val, '-------------')
    const { listName, label, value, childrenName } = fieldConditions
    if (val[listName] && val[listName] instanceof Array) {
        return val[listName].map(item => {
            return {
                ...item,
                label: item[label],
                value: item[value],
                name: item[label],
                children: item[childrenName] ? filterList(item[childrenName], fieldConditions) : null
            }
        })
    }
}
const Radio = (props) => {
    const { onClose, onChange, data, openKey = {} } = props
    const { fieldConditions = {}, value, require } = openKey
    const { listName } = fieldConditions
    return <View onClick={(e) => {
        e.stopPropagation()
    }} className='PublicSettingDrawer_check_list'>
        {openKey[listName] && openKey[listName].map(val => {
            return <View onClick={(e) => {
                if (val[fieldConditions['value']] !== data[value]) {
                    onChange({
                        [value]: val[fieldConditions['value']]
                    })
                    onClose()
                } else {
                    if (require === '1') {
                        return
                    }
                    onChange({
                        [value]: ''
                    })
                    onClose()
                }
            }} className={data[value] === val[fieldConditions['value']] ? 'PublicSettingDrawer_check_val PublicSettingDrawer_check_valCheck' : 'PublicSettingDrawer_check_val'}>
                {val[fieldConditions['label']]}
            </View>
        })}
    </View>
}
const TwoKeyRadio = (props) => {
    const { onClose, onChange, data, openKey = {} } = props
    const { fieldConditions = {}, value } = openKey
    const { listName } = fieldConditions
    const keyList = JSON.parse(value)
    return <View onClick={(e) => {
        e.stopPropagation()
    }} className='PublicSettingDrawer_check_list'>
        {openKey[listName] && openKey[listName].map(val => {
            const valueList = JSON.parse(val[fieldConditions['value']])
            const payload = {}
            return <View onClick={(e) => {
                if (JSON.stringify(keyList.map(val => { return data[val] })) !== val[fieldConditions['value']]) {
                    keyList.forEach((s, o) => {
                        payload[s] = valueList[o]
                    })
                    onChange({
                        ...payload
                    })
                    onClose()
                } else {
                    keyList.forEach((s, o) => {
                        payload[s] = ''
                    })
                    onChange({
                        ...payload
                    })
                    onClose()
                }
            }} className={JSON.stringify(keyList.map(val => { return data[val] })) === val[fieldConditions['value']] ? 'PublicSettingDrawer_check_val PublicSettingDrawer_check_valCheck' : 'PublicSettingDrawer_check_val'}>
                {val[fieldConditions['label']]}
            </View>
        })}
    </View>
}
const LinkageRadio = (props) => {
    const { onClose, onChange, data, openKey = {} } = props
    const { fieldConditions, value } = openKey
    const [list, setList] = useState([])
    const [defaultData, setDetaultData] = useState({})
    const [initList, setInitList] = useState([])
    const [initIndex, setInitIndex] = useState({})
    useEffect(() => {
        setList(filterList(openKey, fieldConditions))
        setDetaultData({
            value: data[value]
        })
    }, [])
    console.log(initList, '12313')
    useEffect(() => {
        const newList = findNodePath(list, defaultData.value).filter(val => { return val.value !== defaultData.value })
        const { listName } = fieldConditions
        setInitList([...newList])
        setInitIndex(newList[newList.length - 1] ? newList[newList.length - 1] : {
            ...openKey,
            children: list
        })
    }, [defaultData])
    const { children = [] } = initIndex
    console.log(children)
    return <View className="LinkageRadio_box">
        <View className="LinkageRadio_title_box">
            <View onClick={() => {
                setDetaultData({})
            }} className="LinkageRadio_tab"> <View className={initIndex.value === openKey.value ? 'LinkageRadio_tab_font LinkageRadio_tab_active' : 'LinkageRadio_tab_font'}>{openKey.name}
                </View></View>
            {initList.map((val, index) => {
                return <View onClick={() => {
                    setInitIndex(val)
                    setInitList(initList.filter((val, key) => {
                        return key <= index
                    }))

                }} className="LinkageRadio_tab"> <View className={initIndex.value === val.value ? 'LinkageRadio_tab_font LinkageRadio_tab_active' : 'LinkageRadio_tab_font'}>{val.name}
                    </View></View>
            })}
        </View>
        <View className="PublicSettingDrawer_check_list">

            {children.map(val => {
                const { children: listInfo = [] } = val
                return <View onClick={() => {
                    if (listInfo && listInfo.length) {
                        setInitIndex(val)
                        setInitList([...initList, val])
                    } else {
                        onChange({
                            [openKey['value']]: val.value
                        })
                        onClose()
                    }
                }} className={defaultData.value === val.value ? 'PublicSettingDrawer_check_val PublicSettingDrawer_check_valCheck' : 'PublicSettingDrawer_check_val'}> {val.label}</View>
            })}

        </View>
    </View>
}
const LocalRadio = (props) => {
    const { onClose,
        onChange,
        data: params,
        openKey = {},
        visible
    } = props
    const { value } = openKey
    const [activeList, setActiveList] = useState([])
    const [data, setData] = useState([])
    const [active, setActive] = useState(null)
    useEffect(() => {
        if (visible) {
            setActive(City[0].value)
            setActiveList(City[0].children)
            if (params[value]) {
                setData(filterChildrenById(City, params[value].split(',')))
            }
        }
        else {
            setActive(null)
            setActiveList([])
            setData([])
        }
    }, [visible])
    const isSelect = (val) => {
        const flag = data.reduce((item, index) => {
            if (item) {
                return item
            }
            else {
                const { value } = index
                if (value === val) {
                    return true
                } else {
                    return false
                }
            }

        }, false)
        return flag
    }
    const RenderAllView = () => {
        const list = City.reduce((item, index) => {
            if (index.value === active) {

                return index.children
            }
            else {
                return item
            }
        }, [])
        const selectAllList = data.filter(val => {
            return val.pid === active
        })
        if (list.length === selectAllList.length) {
            return <View onClick={() => {
                setData(data.filter(o => {
                    return o.pid !== active
                }))
            }} className='SelectAddress_select_rightItem SelectAddress_select_rightItemCheck'>
                <View>全部</View>
                <View className='SelectAddress_select_select'></View>
            </View>
        } else {
            return <View onClick={() => {
                setData([...list, ...data.filter(val => { return val.pid !== active })])
            }} className='SelectAddress_select_rightItem'>
                <View>全部</View>
                <View className='SelectAddress_select_noSelect'></View>
            </View>

        }
    }
    return <View className='SelectAddress_box'>
        <View className='SelectAddress_body_info'>
            <View className='SelectAddress_body_left'>
                {City.map(val => {
                    const { value, label, children } = val
                    return <View onClick={() => {
                        setActive(value)
                        setActiveList(children)
                    }} className={value === active ? 'SelectAddress_select_item SelectAddress_select_itemCheck' : 'SelectAddress_select_item'}>{label}</View>
                })}

            </View>
            <View className='SelectAddress_body_right'>
                {RenderAllView()}
                {activeList.map(val => {
                    const { value, label } = val
                    if (!isSelect(value)) {
                        return <View onClick={() => {
                            setData([...data, val])
                        }} className='SelectAddress_select_rightItem'>
                            <View>{label}</View>
                            <View className='SelectAddress_select_noSelect'></View>
                        </View>
                    }
                    return <View onClick={() => {
                        setData(data.filter(o => {
                            return o.value !== value
                        }))
                    }} className='SelectAddress_select_rightItem SelectAddress_select_rightItemCheck'>
                        <View>{label}</View>
                        <View className='SelectAddress_select_select'></View>
                    </View>
                })}
            </View>
        </View>
        {data.length > 0 && <View className='SelectAddress_selectTag'>
            {data.map(val => {
                return <View className='SelectAddress_tag'>
                    {val.label}
                    <View onClick={() => {
                        setData(data.filter(o => { return o.value !== val.value }))
                    }} className='SelectAddress_tag_close'></View>
                </View>
            })}
        </View>}
        <View className='SelectAddress_btn_box'>
            <View className='SelectAddress_btn_content'>
                <View onClick={() => {
                    setData([])
                }} className='SelectAddress_btn_style SelectAddress_btn_color1'>
                    重置
                </View>
                <View onClick={() => {
                    onChange({
                        // schoolProvinceCode: active,
                        [value]: data.map(val => { return val.value }).toString()
                    })
                    onClose()
                }} className='SelectAddress_btn_style SelectAddress_btn_color2'>
                    确定
                </View>
            </View>
        </View>
    </View>
}
const TileRadio = (props) => {
    const { visible, onClose, onChange, data: params, openKey = {} } = props
    const { fieldConditions = {}, value, require, queryConditionDefaultParamMap = {} } = openKey
    const { listName } = fieldConditions
    const [data, setData] = useState({})
    useEffect(() => {
        if (visible) {
            setData({ [value]: params[value] })
        }
        else {
            setData({})
        }
    }, [visible])
    return <View>
        <View onClick={(e) => {
            e.stopPropagation()
        }} className='PublicSettingDrawer_check_list'>
            {openKey[listName] && openKey[listName].map(val => {
                return <View onClick={(e) => {
                    if (val[fieldConditions['value']] !== data[value]) {
                        setData({
                            [value]: val[fieldConditions['value']]
                        })

                    } else {
                        if (require === '1') {
                            return
                        }
                        setData({
                            [value]: ''
                        })

                    }
                }} className={data[value] === val[fieldConditions['value']] ? 'PublicSettingDrawer_check_val PublicSettingDrawer_check_valCheck' : 'PublicSettingDrawer_check_val'}>
                    {val[fieldConditions['label']]}
                </View>
            })}

        </View>
        <View className='SelectAddress_btn_box'>
            <View className='SelectAddress_btn_content'>
                <View onClick={() => {
                    setData({
                        ...queryConditionDefaultParamMap,
                    })
                }} className='SelectAddress_btn_style SelectAddress_btn_color1'>
                    重置
                </View>
                <View onClick={() => {
                    onChange({
                        ...data
                    })
                    onClose()
                }} className='SelectAddress_btn_style SelectAddress_btn_color2'>
                    确定
                </View>
            </View>
        </View>
    </View>
}
const SortRadio = (props) => {
    const { visible, onClose, onChange, data, openKey = {} } = props
    const { fieldConditions = {}, value, require } = openKey
    const { label, listName } = fieldConditions
    const keyList = JSON.parse(value)
    return <View className='Sort_Box'>
        {openKey[listName] && openKey[listName].map(val => {
            const valueList = JSON.parse(val[fieldConditions['value']])
            const payload = {}
            return <View onClick={() => {
                if (JSON.stringify(keyList.map(val => { return data[val] })) !== val[fieldConditions['value']]) {
                    keyList.forEach((s, o) => {
                        payload[s] = valueList[o]
                    })
                    onChange({
                        ...payload
                    })
                    onClose()
                } else {
                    if (require === '1') {
                        return
                    }
                    keyList.forEach((s, o) => {
                        payload[s] = ''
                    })
                    onChange({
                        ...payload
                    })
                    onClose()
                }
            }} className={`Sort_List ${JSON.stringify(keyList.map(val => { return data[val] })) === val[fieldConditions['value']] ? 'Sort_List_itemCheck' : ''}`}>
                <View>
                    {val[fieldConditions['label']]}
                </View>
            </View>
        })}
    </View>
}
const TileChecked = (props) => {
    const { visible, onClose, onChange, data: params, openKey = {} } = props
    const { fieldConditions = {}, value, require } = openKey
    const { listName } = fieldConditions
    const [data, setData] = useState([])
    useEffect(() => {
        if (visible) {
            if (params[value]) {
                setData(params[value].split(','))
            }
        }
        else {
            setData([])
        }
    }, [visible])
    const isSelect = (val) => {
        const flag = data.reduce((item, value) => {
            if (item) {
                return item
            }
            else {
                if (value == val) {
                    return true
                } else {
                    return false
                }
            }

        }, false)
        return flag
    }
    console.log(data, '111111111111111')
    return <View>
        <View onClick={(e) => {
            e.stopPropagation()
        }} className='PublicSettingDrawer_check_list'>
            {openKey[listName] && openKey[listName].map(val => {
                return <View onClick={(e) => {
                    if (!isSelect(val[fieldConditions['value']])) {
                        setData([...data, val[fieldConditions['value']]])
                    }
                    else {
                        setData(data.filter(o => {
                            return o !== val[fieldConditions['value']]
                        }))
                    }
                }} className={isSelect(val[fieldConditions['value']]) ? 'PublicSettingDrawer_check_val PublicSettingDrawer_check_valCheck' : 'PublicSettingDrawer_check_val'}>
                    {val[fieldConditions['label']]}
                </View>
            })}

        </View>
        <View className='SelectAddress_btn_box'>
            <View className='SelectAddress_btn_content'>
                <View onClick={() => {
                    setData([])
                }} className='SelectAddress_btn_style SelectAddress_btn_color1'>
                    重置
                </View>
                <View onClick={() => {
                    onChange({
                        [value]: data.toString(),
                    })
                    onClose()
                }} className='SelectAddress_btn_style SelectAddress_btn_color2'>
                    确定
                </View>
            </View>
        </View>
    </View>
}
const BelowTileRadio = (props) => {
    const { visible, onClose, onChange, data, openKey = {} } = props
    const { fieldConditions = {}, value, require } = openKey
    const { label, listName } = fieldConditions
    const defaultDataVGalue = data[value] || ''
    return <View className='Sort_Box'>
        {openKey[listName] && openKey[listName].map(val => {
            return <View onClick={() => {
                if (val[fieldConditions['value']] !== data[value]) {
                    onChange({
                        [value]: val[fieldConditions['value']]
                    })
                    onClose()
                } else {
                    if (require === '1') {
                        return
                    }
                    onChange({
                        [value]: ''
                    })
                    onClose()
                }
            }} className={`Sort_List ${defaultDataVGalue === val[fieldConditions['value']] ? 'Sort_List_itemCheck' : ''}`}>
                <View>
                    {val[fieldConditions['label']]}
                </View>
            </View>
        })}
    </View>
}
const LinkageBottomRadio = (props) => {
    const { visible, onClose, onChange, data, openKey = {} } = props
    const { majorType } = data
    const { fieldConditions = {}, value, require } = openKey
    const { label, listName, childrenName } = fieldConditions
    const [activeList, setActiveList] = useState([])
    const [active, setActive] = useState({})
    const list = openKey[listName]
    function findMajorById(data, targetId) {

        for (const major of data) {
            // 检查当前父类ID是否匹配
            if (major[fieldConditions['value']] === targetId) {
                return {
                    type: 'parent',
                    parent: major
                };
            }

            // 检查子类列表
            if (major[childrenName] && Array.isArray(major[childrenName])) {
                for (const subMajor of major[childrenName]) {
                    if (subMajor[fieldConditions['value']] === targetId) {
                        return {
                            type: 'child',
                            parent: major,
                            child: subMajor
                        };
                    }
                }
            }
        }

        // 未找到匹配项
        return null;
    }
    const newData = findMajorById(list, active) || {}
    const { parent = {}, child = {} } = newData
    useEffect(() => {
        if (visible) {
            const initData = findMajorById(list, data[value]) || {}
            setActive(data[value])
            if (initData.type) {
                setActiveList(initData.parent[childrenName])
            }


        } else {
            setActive(null)
            setActiveList([])
        }

    }, [visible])
    return <View className='SelectAddress_box'>
        <View className='SelectAddress_body_info'>
            <View className='SelectAddress_body_left'>
                <View onClick={() => {
                    setActive(null)
                    onChange({
                        [value]: ''
                    })
                    onClose()
                }} className={(!active) ? 'SelectAddress_select_item SelectAddress_select_itemCheck' : 'SelectAddress_select_item'}>全部</View>
                {list.map(val => {
                    const { [fieldConditions['value']]: id, [label]: majorTypeName, [childrenName]: majorTypeList = [] } = val
                    return <View onClick={() => {
                        setActive(id)
                        setActiveList(majorTypeList)
                    }} className={id === active ? 'SelectAddress_select_item SelectAddress_select_itemCheck' : 'SelectAddress_select_item'}>{majorTypeName}</View>
                })}

            </View>
            <View className='SelectAddress_body_right'>
                {active && <View onClick={() => {
                    onChange({
                        [value]: active
                    })
                    onClose()
                }} className={parent[fieldConditions['value']] === active ? 'SelectAddress_Sort_List SelectAddress_Sort_List_itemCheck' : 'SelectAddress_Sort_List'}>
                    <View>
                        <View className={'SelectAddress_Sort_List_body'}>
                            不限
                        </View>
                    </View>

                </View>}
                {activeList.map(c => {
                    return <>
                        <View onClick={() => {
                            console.log({ [value]: c[fieldConditions['value']] })
                            onChange({
                                [value]: c[fieldConditions['value']]
                            })
                            onClose()
                        }} className={c[fieldConditions['value']] === active ? 'SelectAddress_Sort_List SelectAddress_Sort_List_itemCheck' : 'SelectAddress_Sort_List'}>
                            <View>
                                <View className={'SelectAddress_Sort_List_body '}>
                                    <View className='SelectAddress_Sort_List_itemcontent font_hide'>{c.majorTypeName}</View>
                                    <View className='SelectAddress_Sort_label'>（{c.majorLevel}）</View>
                                </View>
                            </View>

                        </View>
                    </>

                })}
            </View>
        </View>
    </View>
}
const LinkageBottomCheckbox = (props) => {
    const { onClose,
        onChange,
        data: params,
        openKey = {},
        visible
    } = props
    const [data, setData] = useState([])
    const [activeList, setActiveList] = useState([])
    const [active, setActive] = useState(null)
    const { fieldConditions = {}, value, require } = openKey
    const { listName, childrenName, value: fieldValue, label } = fieldConditions
    const list = openKey[listName] || []
    useEffect(() => {
        if (visible) {
            if (params[value]) {
                setData(filterMajorById(list.map(val => { return val[childrenName] || [] }).reduce((item, val) => {
                    return [...item, ...val]
                }, []), params[value].split(','), fieldConditions))

            }
            setActiveList(list[0][childrenName])
            setActive(list[0][fieldValue])
        }
        else {
            setActive(null)
            setActiveList([])
            setData([])
        }
    }, [visible])

    const isSelect = (val) => {
        const flag = data.reduce((item, index) => {
            if (item) {
                return item
            }
            else {
                const { id } = index
                if (id === val) {
                    return true
                } else {
                    return false
                }
            }

        }, false)
        return flag
    }
    return <View className='SelectAddress_box'>
        <View className='SelectAddress_body_info'>
            <View className='SelectAddress_body_left'>
                {list.map(val => {
                    const id = val[fieldValue]
                    return <View onClick={() => {
                        setActive(id)
                        setActiveList(val[childrenName])
                    }} className={id === active ? 'SelectAddress_select_item SelectAddress_select_itemCheck' : 'SelectAddress_select_item'}>{val[label]}</View>
                })}

            </View>
            <View className='SelectAddress_body_right'>
                {activeList.map(c => {
                    const majorList = c[childrenName] || []
                    return <>
                        <View className='SelectAddress_select_rightTitle'>{c[label]}</View>
                        {majorList.map(val => {
                            const id = val[fieldValue]
                            const majorName = val[label]
                            if (!isSelect(id)) {
                                return <View onClick={() => {
                                    setData([...data, val])
                                }} className='SelectAddress_select_rightItem'>
                                    <View>{majorName}</View>
                                    <View className='SelectAddress_select_noSelect'></View>
                                </View>
                            }
                            return <View onClick={() => {
                                setData(data.filter(o => {
                                    return o.id !== id
                                }))
                            }} className='SelectAddress_select_rightItem SelectAddress_select_rightItemCheck'>
                                <View>{majorName}</View>
                                <View className='SelectAddress_select_select'></View>
                            </View>
                        })}

                    </>

                })}
            </View>
        </View>
        {data.length > 0 && <View className='SelectAddress_selectTag'>
            {data.map(val => {
                return <View className='SelectAddress_tag'>
                    {val[label]}
                    <View onClick={() => {
                        setData(data.filter(o => { return o[fieldValue] !== val[fieldValue] }))
                    }} className='SelectAddress_tag_close'></View>
                </View>
            })}
        </View>}
        <View className='SelectAddress_btn_box'>
            <View className='SelectAddress_btn_content'>
                <View onClick={() => {
                    setData([])
                }} className='SelectAddress_btn_style SelectAddress_btn_color1'>
                    重置
                </View>
                <View onClick={() => {
                    onChange({
                        major: data,
                        [value]: data.map(val => { return val[fieldValue] }).toString()
                    })
                    onClose()
                }} className='SelectAddress_btn_style SelectAddress_btn_color2'>
                    确定
                </View>
            </View>
        </View>
    </View>
}
const ChildrenQueryCondition = (props) => {
    const {
        onClose,
        onChange,
        data: params,
        openKey = {},
        visible
    } = props
    const [data, setData] = useState({})
    const { fieldConditions: field = {}, require } = openKey
    const { listName, childrenName, value: fieldValue, label } = field
    const list = openKey[listName] || []
    console.log(data, 'data,,,,,,,,,,,,,,')
    const renderContent = (item) => {
        if (item.type === 'radio') {
            const { fieldConditions = {}, value: submitValue, name, require } = item
            const { value: fieldValue, listName, label } = fieldConditions
            return <>
                <View className='FilterData_content_title'>{name}</View>
                <View className='FilterData_content_item'>
                    {item[listName].map(val => {
                        const name = val[label]
                        const value = val[fieldValue]
                        return <View onClick={() => {
                            if (value === params[value]) {
                                if (require === '1') { return }
                                setData({
                                    ...data,
                                    [submitValue]: ''
                                })
                            }
                            else {
                                setData({
                                    ...data,
                                    [submitValue]: value
                                })
                            }
                        }} className={`FilterData_content_tag ${value === data[submitValue] ? 'FilterData_content_tagCheck' : ''}`}>{name}</View>
                    })}
                </View>
            </>
        }
        else if (item.type === 'sortRadio') {
            const { fieldConditions, value, name } = item
            const keyList = JSON.parse(value)
            return <>
                <View className='FilterData_content_title'>{name}</View>
                <View className='FilterData_content_item'>
                    {item[fieldConditions["listName"]].map(val => {
                        const valueList = JSON.parse(val[fieldConditions['value']])
                        return <View onClick={() => {
                            const payload = {}
                            if (JSON.stringify(keyList.map(val => { return data[val] })) !== val[fieldConditions['value']]) {
                                keyList.forEach((s, o) => {
                                    payload[s] = valueList[o]
                                })
                                setData({
                                    ...data,
                                    ...payload
                                })

                            } else {
                                if (require === '1') {
                                    return
                                }
                                keyList.forEach((s, o) => {
                                    payload[s] = ''
                                })
                                setData({
                                    ...data,
                                    ...payload
                                })

                            }
                        }} className={`FilterData_content_tag ${JSON.stringify(keyList.map(val => { return data[val] })) === val[fieldConditions['value']] ? 'FilterData_content_tagCheck' : ''}`}>{val[fieldConditions['label']]}</View>
                    })}
                </View>
            </>
        } else if (item.type === 'rangeCheckbox') {
            const { fieldConditions, value, name } = item
            const keyList = JSON.parse(value)
            const min = keyList[0]
            const max = keyList[1]
            return <>
                <View className='FilterData_content_title'>{name}</View>
                <View className='FilterData_content_InputBox'>
                    <Input onInput={(e) => {

                        setData({
                            ...data,
                            [min]: e.target.value
                        })
                    }} value={data[min]} placeholderClass='FilterData_content_Inputdega' placeholder={`最低${name}`} className='FilterData_content_Input'></Input>
                    <View className=''>至</View>
                    <Input onInput={(e) => {


                        setData({
                            ...data,
                            [max]: e.target.value
                        })
                    }} value={data[max]} placeholderClass='FilterData_content_Inputdega' placeholder={`最高${name}`} className='FilterData_content_Input'></Input>
                </View >
            </>
        } else if (item.type === 'manyToManyCheckbox') {
            const { fieldConditions = {}, value: submitValue, name, require, max = 3 } = item
            const { value: fieldValue, listName, label } = fieldConditions
            const paramsList = data[submitValue] ? data[submitValue].split(',') : []
            console.log(paramsList, 'paramsList.................')
            const filterIncludes = (id) => {
                return paramsList.includes(id)
            }
            const SubjectHandle = (value) => {
                if (filterIncludes(value)) {
                    setData({
                        ...data,
                        [submitValue]: paramsList.filter(val => {
                            return val !== value
                        }).toString()
                    })
                }
                else {
                    if (paramsList.length >= max) {
                        toast('最多可选3个')
                    } else {
                        setData({
                            ...data,
                            [submitValue]: [...paramsList, value].toString()
                        })
                    }
                }
            }
            return <>
                <View className='FilterData_content_title'>{name}</View>
                <View className='FilterData_content_item'>
                    {item[listName].map(val => {
                        return <View onClick={() => {
                            SubjectHandle(val[fieldValue])
                        }} className={`FilterData_content_tag ${filterIncludes(val[fieldValue]) ? 'FilterData_content_tagCheck' : ''}`}>{val[label]}</View>
                    })}
                </View>
            </>
        }
        return null
    }
    const initParams = () => {
        return list.reduce((val, item) => {
            const { value, type } = item
            if (type === 'sortRadio' || type === 'rangeCheckbox') {
                const keyList = JSON.parse(value)
                const payload = {}
                keyList.map(o => {
                    payload[o] = params[o]
                })
                return {
                    ...val,
                    ...payload,
                }
            }
            return {
                ...val,
                [value]: params[value]
            }
        }, {})
    }
    const reloadParams = () => {
        return list.reduce((val, item) => {
            const { value, type, require, defaultParamMap = {} } = item
            if (require === '1') {
                return {
                    ...val,
                    ...defaultParamMap
                }
            }
            else if (type === 'sortRadio' || type === 'rangeCheckbox') {
                const keyList = JSON.parse(value)
                const payload = {}
                keyList.map(o => {
                    payload[o] = ''
                })
                return {
                    ...val,
                    ...payload,
                }
            }
            return {
                ...val,
                [value]: ''
            }
        }, data)
    }

    useEffect(() => {
        if (visible) {
            setData(initParams())
        }
        else {
            setData({})
        }
    }, [visible])
    return <View className='FilterData_box'>
        <View className='FilterData_body_info'>
            <View className='FilterData_content'>
                {list.map(val => {
                    return renderContent(val)
                })}
            </View>
        </View>
        <View className='SelectAddress_btn_box'>
            <View className='SelectAddress_btn_content'>
                <View onClick={() => {
                    setData(reloadParams())
                }} className='SelectAddress_btn_style SelectAddress_btn_color1'>
                    重置
                </View>
                <View onClick={() => {
                    onChange({
                        ...data
                    })
                    onClose()
                }} className='SelectAddress_btn_style SelectAddress_btn_color2'>
                    确定
                </View>
            </View>
        </View>
    </View>
}
const LocalOutsideResetRadio = (props) => {
    const {
        onClose,
        onChange,
        data: params,
        openKey = {},
        visible
    } = props
    const [data, setData] = useState({})
    const { value: saveValue } = openKey
    useEffect(() => {
        if (visible) {
            setData({
                [saveValue]: params[saveValue]
            })
        }
        else {
            setData({})
        }
    }, [visible])
    return <View className='FilterData_box'>
        <View className='FilterData_body_info'>
            <View className='FilterData_content'>
                <View className='FilterData_content_title'>选择省份</View>
                <View className='FilterData_content_item'>
                    {City.map(val => {
                        const { label, value } = val
                        return <View onClick={() => {
                            if (value === data[saveValue]) {
                                setData({
                                    ...data,
                                    [saveValue]: ''
                                })
                            }
                            else {
                                setData({
                                    ...data,
                                    [saveValue]: value
                                })
                            }
                        }} className={`FilterData_content_tag ${value === data[saveValue] ? 'FilterData_content_tagCheck' : ''}`}>{label}</View>
                    })}
                </View>
            </View>
        </View>
        <View className='SelectAddress_btn_box'>
            <View className='SelectAddress_btn_content'>
                <View onClick={() => {
                    setData({
                        [saveValue]: ''
                    })
                }} className='SelectAddress_btn_style SelectAddress_btn_color1'>
                    重置
                </View>
                <View onClick={() => {
                    onChange({
                        ...data
                    })
                    onClose()
                }} className='SelectAddress_btn_style SelectAddress_btn_color2'>
                    确定
                </View>
            </View>
        </View>
    </View>
}
const PublicSettingDrawer = (props) => {
    const { selectList = [], params = {}, onChange, openType = 'pop', onChangeVisible } = props
    const [visible, setVisible] = useState(false)
    const [openKeyData, setOpenKeyData] = useState({})
    const { type } = openKeyData
    useEffect(() => {
        onChangeVisible && onChangeVisible(visible)
    }, [visible])
    const OpenDown = (val) => {
        setVisible({
            show: true,
            detail: params,
        })
        setOpenKeyData(val)
    }
    const onClose = () => {
        setVisible(false)
        setOpenKeyData({})
    }
    const filterCodeName = (val, defaultName) => {
        const { type, fieldConditions = {}, value: keyName } = val
        if (type === 'radio' || type === 'tileRadio' || type === 'belowTileRadio' || type === '') {
            const { label, value, listName } = fieldConditions
            return val[listName].reduce((item, val) => {
                if (val[value] === params[keyName]) {
                    return val[label]
                }
                return item
            }, val.name)
        } else if (type === 'linkageRadio') {
            const list = filterList(val, fieldConditions)
            const note = findNodePath(list, params[keyName])
            return note.reduce((e, val) => {
                return val.label
            }, val.name)
        } else if (type === 'twoKeyRadio' || type === 'sortRadio') {
            const { fieldConditions = {}, value: keyName } = val
            const keyList = JSON.parse(keyName)
            const { label, value, listName } = fieldConditions
            const dataInfo = keyList.map(val => { return params[val] })
            return val[listName].reduce((item, val) => {
                if (val[value] === JSON.stringify(dataInfo)) {
                    return val[label]
                }
                return item
            }, val.name)
        } else if (type === 'localCheckbox') {
            const cityCodes = params[keyName] ? params[keyName].split(',') : []
            if (cityCodes.length > 0) {
                return filterChildrenById(City, cityCodes).map(val => { return val.label }).toString()
            }
        } else if (type === 'linkageBottomRadio') {
            const { childrenName, value, listName } = fieldConditions
            function findMajorById(data, targetId) {
                for (const major of data) {
                    // 检查当前父类ID是否匹配
                    if (major[value] === targetId) {
                        return {
                            type: 'parent',
                            parent: major
                        };
                    }
                    // 检查子类列表
                    if (major[childrenName] && Array.isArray(major[childrenName])) {
                        for (const subMajor of major[childrenName]) {
                            if (subMajor[value] === targetId) {
                                return {
                                    type: 'child',
                                    parent: major,
                                    child: subMajor
                                };
                            }
                        }
                    }
                }

                // 未找到匹配项
                return null;
            }
            const newData = findMajorById(val[listName], params[keyName])
            console.log(newData, val[listName], params, '========newData')
            if (newData) {
                if (newData.type === 'parent') {
                    return newData.parent[fieldConditions['label']]
                }
                else {
                    return newData.child[fieldConditions['label']]
                }
            }
            else {
                return defaultName
            }

        } else if (type === 'tileCheckbox') {
            if (!params[keyName]) {
                return defaultName
            }
            else {
                const RenderStr = []
                const selectList = params[keyName].split(',')
                const { listName, value, label } = fieldConditions
                val[listName].forEach(val => {
                    if (selectList.includes(val[value])) {
                        RenderStr.push(val)
                    }
                })
                return RenderStr.map(val => { return val[label] }).toString()
            }

        } else if (type === 'localOutsideResetRadio') {
            if (!params[keyName]) {
                return defaultName
            }
            else {
                return City.reduce((item, vals) => {
                    const { label, value } = vals
                    if (value === params[keyName]) {
                        return label
                    }
                    return item
                }, '')
            }
        }
        return defaultName
    }
    const RenderView = {
        radio: <Radio openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></Radio>,
        linkageRadio: <LinkageRadio openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></LinkageRadio>,
        twoKeyRadio: <TwoKeyRadio openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></TwoKeyRadio>,
        localCheckbox: <LocalRadio visible={visible} openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></LocalRadio>,
        linkageBottomCheckbox: <LinkageBottomCheckbox visible={visible} openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></LinkageBottomCheckbox>,
        childrenQueryCondition: <ChildrenQueryCondition visible={visible} openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></ChildrenQueryCondition>,
        tileRadio: <TileRadio visible={visible} openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></TileRadio>,
        sortRadio: <SortRadio visible={visible} openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></SortRadio>,
        tileChecked: <TileChecked visible={visible} openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></TileChecked>,
        belowTileRadio: <BelowTileRadio visible={visible} openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></BelowTileRadio>,
        linkageBottomRadio: <LinkageBottomRadio visible={visible} openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></LinkageBottomRadio>,
        tileCheckbox: <TileChecked visible={visible} openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></TileChecked>,
        localOutsideResetRadio: <LocalOutsideResetRadio visible={visible} openKey={openKeyData} data={params} onClose={onClose} onChange={onChange}></LocalOutsideResetRadio>,
    }[type]
    return <>
        <View style={{ gridTemplateColumns: `repeat(${selectList.length > 3 ? selectList.length : 3}, 1fr);` }} className='PublicSettingDrawer_table_title'>
            {selectList.map((val, index) => {
                const { name, value, fieldConditions = {} } = val
                const { listName } = fieldConditions
                const selectData = val[listName]
                return <View onClick={() => {
                    OpenDown(val)
                }}
                    style={openType === 'down' ? { color: openKeyData.value === value ? '#FF2C41' : '#666666', justifyContent: index === 0 ? 'flex-start' : index === selectList.length - 1 ? 'flex-end' : 'center' } : {
                        color: openKeyData.value === value ? '#FF2C41' : '#666666', justifyContent: index === 0 ? 'flex-start' : index === selectList.length - 1 ? 'flex-end' : 'center'
                    }}

                    className={`PublicSettingDrawer_table_tab ${openKeyData.value === value ? 'PublicSettingDrawer_table_tabCheckActive font_hide' : 'PublicSettingDrawer_table_tabActive font_hide'}`}>
                    <View style={filterCodeName(val, name) !== name ? { color: '#FF2C41' } : {}} className="PublicSettingDrawer_tabWidth font_hide">
                        {filterCodeName(val, name)}
                    </View>
                </View>
            })}
        </View >
        <View className="PublicSettingDrawer_up_findIndex"></View>
        {openType === 'down' && <Down selectList={selectList} visible={visible} onClose={onClose}>{RenderView}</Down>}
        {openType === 'pop' && <Pop selectList={selectList} visible={visible} onClose={onClose}>{RenderView}</Pop>}
    </>
}
export default PublicSettingDrawer



